var fs = require('fs');
var path = require('path');
var data = require('gulp-data');
var ejs = require('gulp-ejs');
var gulp = require('gulp');
var gulpSequence = require('gulp-sequence');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var postcss = require('gulp-postcss');
var center = require('postcss-center');
var pxtorem = require('postcss-pxtorem');
var sorting = require('postcss-sorting');
var animation = require('postcss-animations');
var trige = require('postcss-triangle');
var utils = require('postcss-utilities'); // https://github.com/ismamz/postcss-utilities
var rucksack = require('rucksack-css');
var lost = require('lost');
var stylefmt = require('gulp-stylefmt');
var cssmin = require('gulp-clean-css');
var autoprefixer = require('gulp-autoprefixer');
var stylelint = require('stylelint');
var browserSync = require('browser-sync');
var imagemin = require('gulp-imagemin');
var tinypng = require('gulp-tinypng');
var minimist = require('minimist');
var htmlmin = require('gulp-htmlmin');
var htmlBeautify = require('gulp-html-beautify');
var uglify = require('gulp-uglify');
var changed = require('gulp-changed');
var clean = require('gulp-clean');
var rename = require('gulp-rename');
var zip = require('gulp-zip');
var app = require('./config.js');
var base64 = require('gulp-base64'); 
var debug = require('gulp-debug');
var babel = require('gulp-babel');  
var headerComment = require('gulp-header-comment');
var gulpif = require('gulp-if');
gulp.task('js',() => {
    gulp.src('src/js/*.js')
       .pipe(uglify())
       .pipe(rename({suffix: '.min'}))
       .pipe(gulp.dest('./build/js'))
})
gulp.task('scss', () => {
    var browsers = app.device == 'pc' ? app.autoprefixer.pc : app.autoprefixer.mobile;
    gulp.src([app.srcPath+'static/sass/*.css'])
        .pipe(gulp.dest(app.devPath+"/css/"));
    return gulp.src([app.srcPath+'sass/*.scss'])
        .pipe(changed(app.devPath+'css',{extension:'.css'}))
        .pipe(sourcemaps.init())
        
        .pipe(sass().on('error', sass.logError))
        // .pipe(base64(app.base64))
        .pipe(postcss([
            // stylelint({configFile: './.stylelintrc'}),
            trige(),
            center(),
            utils({ 
                ie8: true,
                centerMethod: 'flexbox'
            }),
            animation(app.animation),
            lost(),
            rucksack(),
            app.device =='mobile'? pxtorem(app.pxtorem):sorting(app.sorting),
            sorting(app.sorting)
        ]))
        .pipe(autoprefixer({
            browsers: browsers,
            cascade: false
        }))
        .pipe(cssmin(app.cssmin))
        
        .pipe(headerComment(`
            @created : <%= moment().format('YYYY/MM/DD HH:mm:ss') %>
            @author : <%= _.capitalize(pkg.author) %>
            @desc : <%= pkg.description %>`
        ))
        .pipe(sourcemaps.write('./'))
        .pipe(debug({title: 'Compile style:'})) 
        .pipe(gulp.dest(app.devPath+'css'))
});

gulp.task('stylefmt', () => {
    return gulp.src('test/a.css')
        // .pipe(sass().on('error', sass.logError))
        .pipe(stylefmt({configFile: './.stylelintrc'}))
        .pipe(postcss([
            stylelint({configFile: './.stylelintrc'})
        ]))
        .pipe(sourcemaps.write('./'))
        .pipe(gulp.dest('test/aaa/'));
});

gulp.task('script',() => {
    gulp.src([app.srcPath+'static/**/*.js'])
        .pipe(changed(app.devPath))
        .pipe(debug({title: 'Compile js:'}))   
        .pipe(gulp.dest(app.devPath));
    gulp.src([app.srcPath+'js/*.js'])
        // .pipe(changed(app.devPath+'/js'))
        .pipe(headerComment(`
		    @created : <%= moment().format('YYYY/MM/DD HH:mm:ss') %>
		    @author : <%= _.capitalize(pkg.author) %>
		    @desc : <%= pkg.description %>`
        ))
        // .pipe(babel({
        //     presets: ['es2015']
        // }))
        .pipe(debug({title: 'Compile js:'}))   
        .pipe(gulp.dest(app.devPath+'/js'))
});

// gulp.task('img', () => {
//     return gulp.src([app.srcPath+'images/*.{png,jpg}'])
//         .pipe(changed(app.devPath+'images'))
//         .pipe(gulpif(app.imgCompress,tinypng(app.tinypngCode),imagemin()))
//         .pipe(debug({title: 'Compile png:'})) 
//         .pipe(gulp.dest(app.devPath+'images'))
//     // return gulp.src([app.srcPath+'images/**/*'])
//     //     .pipe(changed(app.devPath+'images'))
//     //     .pipe(debug({title: 'Compile png:'})) 
//     //     .pipe(gulp.dest(app.devPath+'images'))
// });
var smushit = require('gulp-smushit');
gulp.task('img', () => {
    return gulp.src([app.srcPath+'images/*.{png,jpg}'])
        .pipe(changed(app.devPath+'images'))
        .pipe(smushit({
            verbose: true
        }))
        .pipe(debug({title: 'Compile png:'})) 
        .pipe(gulp.dest(app.devPath+'images'))
});


gulp.task('gulp-ejs', () => {
    return gulp.src(app.srcPath+'*.html')
        .pipe(data(function (file) {
            var filePath = file.path;
            var obj = Object.assign(
                JSON.parse(fs.readFileSync('./ejs/global.json')),
                {device:require('./config.js').device},
                {
                    local: JSON.parse(fs.readFileSync( path.join(path.dirname(filePath), path.basename(filePath, '.html') + '.json')))
                });
            return obj;
        }))
        // .pipe(changed(app.devPath))
  　    .pipe(ejs().on('error', function(err) {
  　　　　/* gutil.log(err);
  　　　　this.emit('end'); */
  　    }))
        .pipe(htmlmin(app.htmlmin))
        .pipe(htmlBeautify(app.htmlBeautify))
        .pipe(debug({title: 'Compile html:'})) 
        .pipe(gulp.dest(app.devPath));
});
function readFile(path) {
    var filesList = [];
    files = fs.readdirSync(path);//需要用到同步读取 
    files.forEach(walk);
    function walk(file) {
        states = fs.statSync(path + '/' + file);
        if (states.isDirectory()) {
            readFile(path + '/' + file, filesList);
        }
        else {
            if(states.size > 8 * 1024){
                filesList.push('build/images/'+file);
            }
        }
    }
    return filesList;
}
gulp.task('copyPro1', async () => {
    var filter = require('gulp-filter');
    var arr = readFile(app.devPath + 'images');
    var cache = './.cache/';
    console.log(arr);
    await gulp.src(['./build/**/*','!./build/images/*'])
        .pipe(gulp.dest('./.cache/'));
    await gulp.src(app.devPath + 'images/*')
        .pipe(filter(arr))
        .pipe(gulp.dest(cache + 'images/'));
    return ;
    
});

gulp.task('copyPro2',async () => { 
    var options = minimist(process.argv.slice(2), app.knownOptions);
    var date = new Date().getTime();
    if(options.env != ''){
        // 保存src开发目录
        gulp.src([app.srcPath+'/**/*'])
            .pipe(gulp.dest(app.prdPath+options.env+date+'/src/'));
        // 保存至svn目录
        gulp.src(['./.cache/**/*', '!./cache/css/*.map'])
            .pipe(gulp.dest(app.svnPath+'/'+options.path+'/'+options.env+'/dist/'));
        // 保存build目录
        gulp.src(['./.cache/**/*'])
            .pipe(gulp.dest(app.prdPath+options.env+date+'/dist/'));
        // 生成zip压缩文件
        return gulp.src(['./.cache/**/*', '!./.cache/css/*.map'])
            .pipe(zip(options.env+'.zip'))
            .pipe(gulp.dest(app.prdPath+options.env+date+'/'));
    } else {
        console.log('请输入项目名称(--env)，重新打包');
    }
});
gulp.task('cc',() => { 
    gulp.src(['./build/**/*','!./build/images/*'])
        .pipe(gulp.dest('./.cache'));
    gulp.src(['./build/images/*'])
        .pipe(imagemin())
        .pipe(gulp.dest('./.cache'));
    return gulp.src('./.cache')
        .pipe(clean());
    
});

gulp.task('server',() => { 
    var options = minimist(process.argv.slice(2), app.knownOptions);
    var dir  = options.name + '.html' || '/';
    browserSync.init({ 
        port:"3000",
        server: app.devPath,
        index:dir
    });  
});

gulp.task('watch',() => {
    gulp.watch([app.srcPath + '**/*.scss'], ['scss']);
    gulp.watch([app.srcPath + '**/*.js'], ['script']);
    gulp.watch([app.srcPath + '**/*.html',app.srcPath + '**/*.json','./ejs/**/*',app.srcPath + 'components/*.ejs'], ['gulp-ejs']);
    gulp.watch([app.devPath + '**/*']).on('change', browserSync.reload); 
})
gulp.task('clean',() => {
    return gulp.src([app.srcPath,app.devPath,'./.gulp/','./.cache/'])
        .pipe(clean());
})
gulp.task('createDir',() => {
    var options = minimist(process.argv.slice(2), app.knownOptions);
    gulp.src(['./temp/**/*','!./temp/**/index*'])
       .pipe(gulp.dest('./src'));
    return gulp.src('temp/**/index*')
       .pipe(rename({basename: options.name}))
       .pipe(gulp.dest('./src'));
})

gulp.task('modify',() => {
    var options = minimist(process.argv.slice(2), app.knownOptions);
    var fs = require('fs');
    var data = fs.readFileSync('./src/'+options.name+'.json','utf-8');
    var radefile = data.replace(/index/g, options.name);
    radefile = radefile.replace(/未定义/g, options.title);
    fs.writeFileSync('./src/'+options.name+'.json',radefile);
    return false;
})
gulp.task('createPageDir',() => {
    var options = minimist(process.argv.slice(2), app.knownOptions);
    var src = app.complete || typeof(options.complete) == 'string' ? 'temp/**/index*' : 'temp/index*';
    console.log(src);
    console.log(typeof(options.complete));
    var options = minimist(process.argv.slice(2), app.knownOptions);
    return gulp.src(src)
    .pipe(rename({basename: options.name}))
    .pipe(gulp.dest('./src'));;
})
gulp.task('chagePageName',() => {
    var options = minimist(process.argv.slice(2), app.knownOptions);
    var fs = require('fs');
    var data = fs.readFileSync('./src/'+options.name+'.json','utf-8');
    var radefile = data.replace(/index/g, options.name);
    radefile = radefile.replace(/未定义/g, options.title);
    fs.writeFileSync('./src/'+options.name+'.json',radefile);
    return false;
})
gulp.task('page',(cb) => {
    var options = minimist(process.argv.slice(2), app.knownOptions);
    app.complete || options.complete ? gulpSequence('createPageDir','chagePageName',cb) : gulpSequence('createPageDir',cb); 
})
// gulp.task('copyPro',(cb) => {
//     gulpSequence('copyPro1','copyPro2',cb);
// })
gulp.task('copyPro',() => { 
    var options = minimist(process.argv.slice(2), app.knownOptions);
    var data = new Date().getTime();
    if(options.env != ''){
        // 保存src开发目录
        gulp.src([app.srcPath+'/**/*'])
            .pipe(gulp.dest(app.prdPath+options.env+data+'/src/'));
        // 保存至svn目录
        gulp.src(['./build/**/*', '!./build/css/*.map'])
            .pipe(gulp.dest(app.svnPath+'/'+options.path+'/'+options.env+'/dist/'));
        // 保存build目录
        gulp.src(['./build/**/*'])
            .pipe(gulp.dest(app.prdPath+options.env+data+'/dist/'));
        // 生成zip压缩文件
        gulp.src(['./build/**/*', '!./build/css/*.map'])
            .pipe(zip(options.env+'.zip'))
            .pipe(gulp.dest(app.prdPath+options.env+data+'/'));
    } else {
        console.log('请输入项目名称(--env)，重新打包');
    }
});
gulp.task('create',(cb) => {
    gulpSequence('clean','createDir','modify','default',cb);
})
gulp.task('default',(cb) => {
    gulpSequence('gulp-ejs',['server','scss','script','img','watch'],function(cb){
    })
});



